package org.spruice;

import org.picocontainer.DefaultPicoContainer;
import org.picocontainer.MutablePicoContainer;
import org.spruice.reflect.StringToValue;

import java.util.List;

/**
 * User: mrettig
 * Date: Feb 7, 2009
 * Time: 4:38:08 PM
 */
public class ModuleContext {
    private DefaultPicoContainer _springContext;
    private ModuleLifecycle lifecycle;

    public ModuleContext(DefaultPicoContainer context, SpruiceModule... module) {
        _springContext = context;
        lifecycle = new ModuleLifecycle(_springContext);
        Binder b = new Binder(new CamelCaseNamer(), new StringToValue());
        for (SpruiceModule mod : module) {
            mod.wire(b);
        }
        for (ContextEntry builder : b.getConfigs()) {
            builder.addTo(_springContext, lifecycle);
        }
        lifecycle.init();
    }

    public ModuleContext(SpruiceModule... modle) {
        this(new DefaultPicoContainer(), modle);
    }

    public <T> T get(String s) {
        return (T) _springContext.getComponent(s);
    }

    public MutablePicoContainer getSpringContext() {
        return _springContext;
    }

    public void init() {
        lifecycle.init();
    }

    public void start() {
        _springContext.start();
        lifecycle.start();
    }

    public void stop() {
        _springContext.stop();
        lifecycle.stop();
    }

    public void destroy() {
        _springContext.dispose();
        lifecycle.dispose();
    }

    public <T> T get(Class<T> type) {
        return _springContext.getComponent(type);
    }

    public <T> List<T> getBeansOfType(Class<T> type) {
        return _springContext.getComponents(type);
    }


}
